/**
 * @file	  ADC捕获各种波形频率
 * @brief	  利用ADC采集与定时器来采频
 * @note	  基于正点原子Mini开发版，仅供学习参考
 * @author	  YYJ
 * @email	  2779314051@qq.com
 * @data	  2020/12/20
 */

#include "stm32f10x.h"
#include "delay.h"
#include "lcd.h"
#include "adc.h"
#include "timer.h"
#include "pwm.h"
#include "usart.h"

int Average(int *data);

int main(void)
{	
	char flag=1;
	int time_datas[100]={0},i=0,hz=0;
	int time=0;
	
	delay_init();
	LCD_Init();
	POINT_COLOR=RED;
	TIM1_PWM_Init(999,71);
	TIM_SetCompare1(TIM1,500);
	TIM3_Int_Init(65534,71);
	Adc_Init();
	uart_init(9600);
	while(1)
	{
		if((ADC_flag&0x8000)&&flag)
		{
			time = time_val+(ADC_flag&0x1fff)*65535;
			LCD_ShowNum(30,30,time,10,16);
			hz=(int)(1000000.0/time);
			LCD_ShowNum(30,70,hz,6,16);
			ADC_flag=0;
			time_datas[i]=time;
			i++;
			if (i==100)
			{
				i=0;
				flag=0;
			}
		}
		if (!flag)
		{
			time = Average(time_datas);
			LCD_ShowNum(30,90,time,6,16);
			hz=(int)(1000000.0/time);
			LCD_ShowNum(30,110,hz,6,16);
			flag=1;
		}
	}
}

//滤波，平均值和滤除尖峰
int Average(int *data)
{
	unsigned char i,j,flag_maopao=0;
	int num=0,average;
	

	for (i=1;i<100;i++)//重者沉
	{
		flag_maopao=0;
		for (j=0;j<100-i;j++)
		{
			if (data[j]>data[j+1])
			{
				num=data[j];
				data[j]=data[j+1];
				data[j+1]=num;
				flag_maopao=1;
			}
		}
		if(!flag_maopao)break;//如果标志没被改变则表示已经不需要排序了
	}
	for (i=25; i < 100-25; i++)
	{
		average += data[i];
	}
	average = (int)(average*1.0/(100-50));
	return average;
}